/* eslint-disable jsx-a11y/anchor-has-content */
import { Space, Table, Tag, Button } from 'antd';
import { useEffect, useState } from 'react';
import { useQuery, useQueryClient } from 'react-query';
import useCacheMakeList from '@/hooks/useCacheMakeList';
import request from '@/utils/req';

const columns = [
  {
    title: 'Name',
    dataIndex: 'name',
    key: 'name',
    render: text => <a>{text}</a>,
  },
  {
    title: 'Age',
    dataIndex: 'age',
    key: 'age',
  },
  {
    title: 'Address',
    dataIndex: 'address',
    key: 'address',
  },
  {
    title: 'Tags',
    key: 'tags',
    dataIndex: 'tags',
    render: tags => (
      <span>
        {tags.map(tag => {
          let color = tag.length > 5 ? 'geekblue' : 'green';
          if (tag === 'loser') {
            color = 'volcano';
          }
          return (
            <Tag color={color} key={tag}>
              {tag.toUpperCase()}
            </Tag>
          );
        })}
      </span>
    ),
  },
  {
    title: 'Action',
    key: 'action',
    render: (_, record) => (
      <Space size="middle">
        <a>Invite {record.name}</a>
        <a>Delete</a>
      </Space>
    ),
  },
];

const fetchList = params => {
  return request('/getMockList', {
    params,
  });
};

const ChildComp = () => {
  const [params, setParams] = useState(Date.now());
  const { isFetching, isError, isLoading, data, refetch } = useQuery(['useQuery'], fetchList, {
    staleTime: Infinity, // 永不过期
    cacheTime: 5000,
  });
  const queryClient = useQueryClient();

  useEffect(() => {
    const res = queryClient.invalidateQueries('useQuery');
  }, []);
  if (isLoading) return <div>加载中.......</div>;
  if (isFetching) return <div>更新中.......</div>;
  if (isError) return <div>加载失败</div>;

  return <Button onClick={() => refetch()}>刷新</Button>;
};

const App = () => {
  const [isShow, setIsShow] = useState(false);

  const { list, getList, paginationConfig } = useCacheMakeList({
    api: {
      getList: fetchList,
    },
    params: {
      top: 'topLeft',
    },
  });

  useEffect(() => {
    getList();
  }, []);

  return (
    <div>
      <Button type="primary" onClick={() => setIsShow(!isShow)}>
        {isShow ? '隐藏' : '显示'}
      </Button>
      <br />
      {isShow && (
        <>
          <ChildComp />
          <Table
            columns={columns}
            pagination={{
              position: ['bottom'],
              ...paginationConfig,
            }}
            dataSource={list}
          />
        </>
      )}
    </div>
  );
};
export default App;
